/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.wizards.template;

import cn.easyplatform.entities.beans.list.Header;
import cn.easyplatform.entities.beans.list.ListBean;
import cn.easyplatform.entities.beans.page.PageBean;
import cn.easyplatform.entities.beans.table.TableField;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.entity.CheckCmd;
import cn.easyplatform.studio.cmd.entity.GetEntityCmd;
import cn.easyplatform.studio.utils.StudioUtil;
import cn.easyplatform.studio.web.editors.ComponentEditorCallback;
import cn.easyplatform.studio.web.editors.GridEditorCallback;
import cn.easyplatform.studio.web.editors.TableInfo;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import cn.easyplatform.type.EntityType;
import org.apache.commons.lang3.math.NumberUtils;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class MobilePage1 extends AbstractTemplate {

    private Grid list;

    protected TableInfo selectedTable;

    protected String selectedList;

    @Override
    protected void initComponents(Component root) {
        for (Component c : root.getFellows()) {
            if (c instanceof A || c instanceof Button)
                c.addEventListener(Events.ON_CLICK, this);
        }
        list = (Grid) root.getFellow("list");
        list.addEventListener(Events.ON_CHANGE, this);
        root.getFellow("selectList").addEventListener(Events.ON_CHANGE, this);
    }

    @Override
    protected void dispatch(Event evt) {
        Component c = evt.getTarget();
        if (c == list) {
            selectedTable = (TableInfo) evt.getData();
            onCreate(list, selectedTable);
            selectedList = null;
        } else if (c.getId().equals("selectList")) {
            if (evt.getName().equals(Events.ON_CLICK)) {
                AbstractView
                        .createComponentView(
                                new ComponentEditorCallback(c,
                                        ((Button) c).getLabel()),
                                EntityType.DATALIST.getName(), c).doHighlighted();
            } else {
                this.selectedList = (String) evt.getData();
                onSelect(list, selectedList);
                selectedTable = null;
            }
        } else if (c.getId().equals("addList")) {
            AbstractView.createTableView(
                    new GridEditorCallback(list,
                            Labels.getLabel("wizard.table")), true, evt.getTarget())
                    .doOverlapped("right,center");
        }
    }

    protected String getContent() {
        StringBuilder sb = new StringBuilder();
        String toolbar = null;
        if (sb.length() > 0) {
            toolbar = sb.toString();
            sb.setLength(0);
        }
        sb.append("<vlayout hflex=\"1\" vflex=\"1\">");
        if (toolbar != null) {
            sb.append(toolbar.replace("caption", "div"));
        }
        if (selectedList != null)
            buildList(sb);
        sb.append("</vlayout>");
        return sb.toString();
    }


    protected void buildList(StringBuilder sb) {
        sb.append("<datalist entity=\"").append(selectedList).append("\"")
                .append(" id=\"pageList\"");
        sb.append(
                " hflex=\"1\" vflex=\"1\" durable=\"true\" event=\"open('U')\"")
                .append(" showRowNumbers=\"true\" pageSize=\"20\"")
                .append(" sizedByContent=\"true\" span=\"true\"/>");
    }

    @Override
    public PageBean getEntity() {
        save();
        PageBean pb = new PageBean();
        pb.setAjax(getContent());
        return pb;
    }

    protected String fetchId() {
        String id = (String) list.getRoot().getAttribute("id");
        if (id.length() > 4) {
            // 功能ID：SYSCOM50
            // 页面ID：SYSCOM50PY01
            // 列表ID：SYSCOM50QY01
            // 子表列表：SYSCOM50QY02
            // 子表页面：SYSCOM50PY02
            String suffix = id.substring(id.length() - 4, id.length());
            String preffix = id.substring(0, id.length() - 4);
            if (suffix.startsWith("PY")
                    && NumberUtils.isNumber(suffix.substring(2))) {// 符合id命名规范
                for (int i = 1; i <= 99; i++) {
                    String entityId = preffix + "QY" + (i < 10 ? "0" + i : i);
                    if (!StudioApp.execute(new CheckCmd(entityId))) {
                        id = entityId;
                        break;
                    }
                }
            } else {// 不符合规范的,在页面id的基础上从01开始累加
                for (int i = 1; i <= 99; i++) {
                    String entityId = id + (i < 10 ? "0" + i : i);
                    if (!StudioApp.execute(new CheckCmd(entityId))) {
                        id = entityId;
                        break;
                    }
                }
            }
        } else {// 不符合规范的,在页面id的基础上从01开始累加
            for (int i = 1; i <= 99; i++) {
                String entityId = id + (i < 10 ? "0" + i : i);
                if (!StudioApp.execute(new CheckCmd(entityId))) {
                    id = entityId;
                    break;
                }
            }
        }
        return id;
    }

    protected void save() {
        if (selectedTable != null) {
            ListBean bean = new ListBean();
            bean.setTable(selectedTable.getTable());
            bean.setId(fetchId());
            bean.setType(EntityType.DATALIST.getName());
            bean.setName((String) list.getRoot().getAttribute("name"));
            List<Header> headers = new ArrayList<Header>();
            for (TableField tf : selectedTable.getFields()) {
                Header header = new Header();
                header.setField(tf.getName());
                header.setName(tf.getName());
                header.setTitle(tf.getDescription());
                header.setType(tf.getType());
                headers.add(header);
            }
            bean.setHeaders(headers);
            StudioUtil.save(bean, 'C');
            this.selectedList = bean.getId();
        }
    }

    protected void onSelect(Grid list, String id) {
        ListBean bean = (ListBean) StudioApp.execute(new GetEntityCmd(id));
        list.getColumns().getChildren().clear();
        for (Header header : bean.getHeaders()) {
            Column col = new Column();
            col.appendChild(new Label(header.getTitle()));
            col.setTooltiptext(header.getName());
            col.setAlign(header.getAlign());
            col.setStyle(header.getStyle());
            col.setIconSclass(header.getIconSclass());
            col.setImage(header.getImage());
            if (!Strings.isBlank(header.getWidth()))
                col.setWidth(header.getWidth());
            list.getColumns().appendChild(col);
        }
    }

    protected void onCreate(Grid list, TableInfo selectedTable) {
        list.getColumns().getChildren().clear();
        for (TableField tf : selectedTable.getFields()) {
            Column col = new Column();
            col.setTooltiptext(tf.getName());
            col.appendChild(new Label(tf.getDescription()));
            list.getColumns().appendChild(col);
        }
    }

}
